#ifndef __ROTOR_HPP__
#define __ROTOR_HPP__

#include <string>

#include "RotorIF.hpp"

class Rotor : public RotorIF {
	private:
		std::string m_configuration;
		int offset;
		int count;

	public:
		/**
		 * Initialize rotor with given configuration and initial rotation
		 * e.g. Rotor("AJDKISRUXBLHWTMCQGZNPVOEYF", 'G')
		 */
		Rotor(const std::string configuration, char position) : RotorIF(configuration, position) {
			count = 0;
			offset = position - 'A';
			m_configuration = configuration;
		}

		/**
		 * reset rotor to given inital rotation
		 */
		void reset(char position) {
			offset = position - 'A';
			count = 0;
		}

		/**
		 * step rotor, return true after 26 steps
		 */
		bool advance() {
			offset++;
			offset %= 26;
			count++;
			if (count == 26) {
				count = 0;
				return true;
			}
			return false;
		}

		/**
		 * perform substitution of a character in "forward direction" (towards reflector)
		 */
		char encrypt(char character) const {
			character += offset;
			if (character > 'Z') {
				character -= 26;
			}
			char result = m_configuration[character - 'A'];
			result -= offset;
			if (result < 'A') {
				result += 26;
			}
			return result;
		}

		/**
		 * perform substitution of a character in "reverse direction" (coming from reflector)
		 */
		char decrypt(char character) const {
			character += offset;
			if (character > 'Z') {
				character -= 26;
			}
			char result = m_configuration.find(character) + 'A';
			result -= offset;
			if (result < 'A') {
				result += 26;
			}
			return result;
		}
};
#endif

